﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Web.Services;
using System.Web.Mvc;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security.Roles;
using DotNetNuke.Modules.ActiveSocialMigrator.Data;
using Active.Modules.Social;
using DotNetNuke.Security.Roles.Internal;
using DotNetNuke.Services.FileSystem;
using System.IO;
using System.Data;
using DotNetNuke.Services.Journal;
using DotNetNuke.Modules.ActiveSocialMigrator.Utilities;

namespace DotNetNuke.Modules.ActiveSocialMigrator.Services
{
    [DnnAuthorize]
    public class JournalServiceController : DnnController
    {
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult ConvertJournal(string JournalTypes)
        {
            //Migrate Journal
            var journalDB = new JournalDB();
            var journalCount = 0;
            List<JournalInfo> jitems = null;
            try {
                jitems = journalDB.JournalList(PortalSettings.PortalId, PortalSettings.UserId, -1, -1, -1, 0, 20, string.Empty, 2, string.Empty);
                if (jitems.Count > 0) {
                    journalCount = jitems[0].ItemCount;
                }
            } catch (Exception ex) {

            }
            int RowIndex = 0;
            IFileManager _fileManager = FileManager.Instance;
            IFolderManager _folderManager = FolderManager.Instance;
            var rootFolderPath = PathUtils.Instance.FormatFolderPath(PortalSettings.HomeDirectory);
            string output = "";
            if (journalCount > 0) {
                do {
                    RowIndex = journalCount - 40;
                    if (RowIndex < 0) {
                        RowIndex = 0;
                    }
                    jitems = journalDB.JournalList(PortalSettings.PortalId, PortalSettings.UserId, -1, -1, -1, RowIndex, 40, string.Empty, 2, string.Empty);
                    JournalTypeMapping jtm = new JournalTypeMapping();
                    var groupsDB = new GroupsDB();

                    for (int i = jitems.Count; i-- > 0; ) {
                        JournalInfo ji = jitems[i];
                                   
                        JournalItem coreJournalItem = new JournalItem();
                        int juser = ji.UserId;
                        if (juser < 0) {
                            juser = ji.ProfileUserId;
                        }
                        var journalType = DotNetNuke.Services.Journal.JournalController.Instance.GetJournalType(jtm.MapJournalType(ji.JournalType));
                        coreJournalItem.PortalId = ji.PortalId;
                        coreJournalItem.ProfileId = juser;
                        coreJournalItem.UserId = juser;
                        coreJournalItem.SocialGroupId = -1;
                        if (ji.GroupId > 0) {
                            coreJournalItem.SocialGroupId = groupsDB.GetGroupId(ji.GroupId);
                        }
                        coreJournalItem.AccessKey = ji.AccessKey;
                        coreJournalItem.Summary = ji.Summary;
                        coreJournalItem.Title = ji.Subject;
                        coreJournalItem.DateCreated = ji.DateCreated;
                        coreJournalItem.JournalTypeId = journalType.JournalTypeId;
                        coreJournalItem.ObjectKey = "AS" + ji.JournalId.ToString();
                        try
                        {
                            if (journalType.JournalType == "link")
                            {
                                coreJournalItem.ItemData = new ItemData();
                                coreJournalItem.ItemData.Title = ji.JournalDataItems[0].Title;
                                coreJournalItem.ItemData.Url = ji.JournalDataItems[0].Url;
                                coreJournalItem.Body = null;
                                coreJournalItem.Summary = ji.JournalDataItems[0].Summary;
                                coreJournalItem.ItemData.Description = ji.JournalDataItems[0].Body;
                                if (ji.JournalDataItems[0].ImgUrl != null)
                                {
                                    var pathTemplate = "";
                                    if (ji.GroupId > 0)
                                    {
                                        pathTemplate = PathUtils.Instance.MapPath(String.Format("~/Portals/{0}/activesocial/groups/{1}/gallery", PortalSettings.PortalId, ji.GroupId));
                                    }
                                    else
                                    {
                                        pathTemplate = PathUtils.Instance.MapPath(String.Format("~/Portals/{0}/activesocial/profiles/{1}/gallery", PortalSettings.PortalId, ji.UserId));
                                    }

                                    if (ji.GroupId > 0)
                                    {
                                        if (System.IO.File.Exists(pathTemplate + "\\" + ji.JournalDataItems[0].ImgUrl))
                                        {
                                            var filePath = pathTemplate + "\\" + ji.JournalDataItems[0].ImgUrl;

                                            IFolderInfo groupFolder = _folderManager.GetFolder(PortalSettings.PortalId, "Groups/" + coreJournalItem.SocialGroupId);
                                            if (groupFolder == null)
                                            {
                                                groupFolder = _folderManager.AddFolder(PortalSettings.PortalId, "Groups/" + coreJournalItem.SocialGroupId);
                                            }
                                            if (groupFolder != null)
                                            {
                                                var fileName = Path.GetFileName(filePath);
                                                try
                                                {
                                                    var file = System.IO.File.Open(filePath, FileMode.Open);
                                                    var fileInfo = _fileManager.AddFile(groupFolder, fileName, file);
                                                    var fileString = "fileid=" + fileInfo.FileId;
                                                    coreJournalItem.ItemData.ImageUrl = string.Format("{0}/LinkClick.aspx?fileticket={1}", DotNetNuke.Common.Globals.ApplicationPath, UrlUtils.EncryptParameter(UrlUtils.GetParameterValue(fileString)));

                                                }
                                                catch
                                                {

                                                }


                                            }
                                        }
                                    }

                                }
                            }
                        }
                        catch
                        {
                        }
                        
                        try
                        {
                            if (journalType.JournalType == "file")
                            {
                                coreJournalItem.ItemData = new ItemData();
                                coreJournalItem.ItemData.Title = ji.JournalDataItems[0].Title;
                                coreJournalItem.Body = null;
                                coreJournalItem.Summary = ji.JournalDataItems[0].Summary;

                                var pathTemplate = "";
                                if (ji.GroupId > 0)
                                {
                                    pathTemplate = PathUtils.Instance.MapPath(String.Format("~/Portals/{0}/activesocial/groups/{1}/files", PortalSettings.PortalId, ji.GroupId));
                                }
                                else
                                {
                                    pathTemplate = PathUtils.Instance.MapPath(String.Format("~/Portals/{0}/activesocial/profiles/{1}/files", PortalSettings.PortalId, ji.UserId));
                                }
                                if (ji.GroupId > 0)
                                {
                                    if (System.IO.File.Exists(pathTemplate + "\\" + ji.JournalDataItems[0].Title))
                                    {
                                        var filePath = pathTemplate + "\\" + ji.JournalDataItems[0].Title;
                                        IFolderInfo groupFolder = _folderManager.GetFolder(PortalSettings.PortalId, "Groups/" + coreJournalItem.SocialGroupId);
                                        if (groupFolder == null)
                                        {
                                            groupFolder = _folderManager.AddFolder(PortalSettings.PortalId, "Groups/" + coreJournalItem.SocialGroupId);
                                        }
                                        if (groupFolder != null)
                                        {
                                            var fileName = Path.GetFileName(filePath);
                                            var file = System.IO.File.Open(filePath, FileMode.Open);
                                            var fileInfo = _fileManager.AddFile(groupFolder, fileName, file);
                                            var fileString = "fileid=" + fileInfo.FileId;
                                            coreJournalItem.ItemData.Url = string.Format("{0}/LinkClick.aspx?fileticket={1}", DotNetNuke.Common.Globals.ApplicationPath, UrlUtils.EncryptParameter(UrlUtils.GetParameterValue(fileString)));
                                            var fileIcon = Entities.Icons.IconController.IconURL("Ext" + fileInfo.Extension, "32x32");
                                            if (!System.IO.File.Exists(PathUtils.Instance.MapPath(fileIcon)))
                                            {
                                                fileIcon = Entities.Icons.IconController.IconURL("File", "32x32");
                                            }
                                            if (!String.IsNullOrEmpty(fileIcon))
                                            {
                                                coreJournalItem.ItemData.ImageUrl = fileIcon;
                                            }
                                        }
                                    }
                                }

                            }
                        }
                        catch
                        {
                        }

                        try
                        {
                            if (journalType.JournalType == "photo")
                            {
                                coreJournalItem.ItemData = new ItemData();
                                coreJournalItem.ItemData.Title = ji.JournalDataItems[0].Title;
                                coreJournalItem.Body = null;
                                coreJournalItem.Summary = ji.JournalDataItems[0].Summary;

                                var pathTemplate = PathUtils.Instance.MapPath(ji.JournalDataItems[0].ImgUrl);
                                if (ji.GroupId > 0)
                                {
                                    if (System.IO.File.Exists(pathTemplate + "lg\\" + ji.JournalDataItems[0].Title))
                                    {
                                        var filePath = pathTemplate + "lg\\" + ji.JournalDataItems[0].Title;
                                        IFolderInfo groupFolder = _folderManager.GetFolder(PortalSettings.PortalId, "Groups/" + coreJournalItem.SocialGroupId);
                                        if (groupFolder == null)
                                        {
                                            groupFolder = _folderManager.AddFolder(PortalSettings.PortalId, "Groups/" + coreJournalItem.SocialGroupId);
                                        }
                                        if (groupFolder != null)
                                        {
                                            var fileName = Path.GetFileName(filePath);
                                            try
                                            {
                                                var file = System.IO.File.Open(filePath, FileMode.Open);
                                                var fileInfo = _fileManager.AddFile(groupFolder, fileName, file);
                                                var fileString = "fileid=" + fileInfo.FileId;
                                                coreJournalItem.ItemData.Url = string.Format("{0}/LinkClick.aspx?fileticket={1}", DotNetNuke.Common.Globals.ApplicationPath, UrlUtils.EncryptParameter(UrlUtils.GetParameterValue(fileString)));
                                                coreJournalItem.ItemData.ImageUrl = FileManager.Instance.GetUrl(fileInfo);
                                            }
                                            catch
                                            {

                                            }

                                        }
                                    }
                                }

                            }
                        }
                        catch
                        {
                        }
                       
                        try {
                            DotNetNuke.Services.Journal.JournalController.Instance.SaveJournalItem(coreJournalItem, 1);
                        } catch (Exception ex) {
                        }

                        journalDB.UpdateJournalDates(ji.JournalId, ji.DateCreated);
                        try {
                            journalDB.MoveComments(ji.JournalId);
                        } catch {

                        }
                        
                    }

                } while (RowIndex > 0);
                
                

            }





            return Json(new { Result = output });
        }
        
    }
}